<template>
  <div class="app-container">
    <!-- 头部搜索区域 -->
    <el-card >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.reportNo" placeholder="请输入报表编号" clearable />
        </el-col>
        <el-col :span="10">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待处理" value="待处理" />
            <el-option label="待审核" value="待审核" />
            <el-option label="已处理" value="已处理" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 报表表格区域 -->
    <el-card class="mt-2">
      <div class="table-header">
        <el-button type="success" @click="showCreateDialog = true">新建报表</el-button>
      </div>
      
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="reportNo" label="报表编号" width="180" />
        <el-table-column prop="reportName" label="报表名称" />
        <el-table-column prop="createTime" label="填报时间" width="180" />
        <el-table-column prop="creator" label="填报人" width="120" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看详情</el-button>
            <el-button 
              v-if="row.status === '待审核' || row.status === '待处理'" 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-dropdown v-if="row.status === '待审核'" trigger="click">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleApprove(row)">审核通过</el-dropdown-item>
                  <el-dropdown-item @click="handleReject(row)">审核驳回</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建报表对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建水质化验报表" width="70%">
      <el-form 
        ref="reportForm"
        :model="newReportForm" 
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报表名称" prop="reportName">
              <el-input v-model="newReportForm.reportName" placeholder="请输入报表名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采样地点" prop="samplingLocation">
              <el-input v-model="newReportForm.samplingLocation" placeholder="请输入采样地点" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采样时间" prop="samplingTime">
              <el-date-picker
                v-model="newReportForm.samplingTime"
                type="datetime"
                placeholder="选择采样时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测人员" prop="inspector">
              <el-input v-model="newReportForm.inspector" placeholder="请输入检测人员姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider />
        
        <h3>水质检测数据</h3>
        <el-table :data="newReportForm.testItems" border style="width: 100%; margin-bottom: 20px">
          <el-table-column prop="item" label="检测项目" width="200">
            <template #default="{ $index }">
              <el-select 
                v-model="newReportForm.testItems[$index].item" 
                placeholder="请选择检测项目"
                style="width: 100%"
                @change="handleTestItemChange($index)"
              >
                <el-option 
                  v-for="item in testItemOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="检测值">
            <template #default="{ $index }">
              <el-input 
                v-model="newReportForm.testItems[$index].value" 
                placeholder="请输入检测值"
                @blur="validateTestValue($index)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="120">
            <template #default="{ row }">
              {{ standardRanges[row.item]?.unit || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="standard" label="标准值" width="150">
            <template #default="{ row }">
              {{ standardRanges[row.item] ? `${standardRanges[row.item].min}~${standardRanges[row.item].max}` : '' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button 
                type="danger" 
                size="small" 
                :icon="Delete" 
                circle 
                @click="removeTestItem($index)"
              />
            </template>
          </el-table-column>
        </el-table>
        
        <el-button type="primary" @click="addTestItem">+ 添加检测项目</el-button>
        
        <el-divider />
        
        <el-form-item label="备注信息">
          <el-input
            v-model="newReportForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReport">提交报表</el-button>
      </template>
    </el-dialog>

    <!-- 报表详情对话框 -->
    <el-dialog v-model="showDetailDialog" :title="`水质化验报表详情 - ${currentReport.reportNo}`" width="70%">
      <div class="detail-container">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报表编号">{{ currentReport.reportNo }}</el-descriptions-item>
          <el-descriptions-item label="报表名称">{{ currentReport.reportName }}</el-descriptions-item>
          <el-descriptions-item label="采样地点">{{ currentReport.samplingLocation }}</el-descriptions-item>
          <el-descriptions-item label="采样时间">{{ currentReport.samplingTime }}</el-descriptions-item>
          <el-descriptions-item label="检测人员">{{ currentReport.inspector }}</el-descriptions-item>
          <el-descriptions-item label="填报人">{{ currentReport.creator }}</el-descriptions-item>
          <el-descriptions-item label="填报时间">{{ currentReport.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentReport.status)">{{ currentReport.status }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <h3>水质检测数据</h3>
        <el-table :data="transformTestData(currentReport)" border style="width: 100%">
          <el-table-column prop="item" label="检测项目" width="200" />
          <el-table-column prop="value" label="检测值" />
          <el-table-column prop="unit" label="单位" width="120" />
          <el-table-column prop="standard" label="标准值" width="150" />
          <el-table-column label="结果判定" width="120">
            <template #default="{ row }">
              <el-tag :type="row.result === '合格' ? 'success' : 'danger'">{{ row.result }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <el-divider />
        
        <h3>备注信息</h3>
        <el-input
          v-model="currentReport.remarks"
          type="textarea"
          :rows="3"
          readonly
        />
        
        <el-divider v-if="currentReport.operationRecords?.length" />
        
        <h3 v-if="currentReport.operationRecords?.length">操作记录</h3>
        <el-timeline v-if="currentReport.operationRecords?.length">
          <el-timeline-item
            v-for="(record, index) in currentReport.operationRecords"
            :key="index"
            :timestamp="record.time"
          >
            {{ record.action }} - {{ record.operator }}
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button 
          v-if="currentReport.status === '待审核'" 
          type="success" 
          @click="handleApprove(currentReport)"
        >
          审核通过
        </el-button>
        <el-button 
          v-if="currentReport.status === '待审核'" 
          type="warning" 
          @click="handleReject(currentReport)"
        >
          审核驳回
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, ArrowDown } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  reportNo: '',
  dateRange: [],
  status: ''
})

// 表格数据
const tableData = ref([
  {
    reportNo: 'WQR-202503001',
    reportName: '3月27日水质化验报表',
    samplingLocation: '消毒池',
    samplingTime: '2025-03-27 08:00',
    createTime: '2025/3/27 15:13:28',
    creator: '张明远',
    inspector: '李亚明',
    status: '已处理',
    testItems: [
      { item: 'pH值', value: '8.1', unit: '', standard: '6.5~8.5', result: '合格' },
      { item: '浊度', value: '1.45', unit: 'NTU', standard: '≤1', result: '不合格' },
      { item: '余氯', value: '0.10', unit: 'mg/L', standard: '≥0.05', result: '合格' },
      { item: '总大肠菌群', value: '2', unit: 'CFU/10mL', standard: '不得检出', result: '不合格' },
      { item: '氨氮', value: '0.59', unit: 'mg/L', standard: '≤0.5', result: '不合格' }
    ],
    remarks: '水质总体合格，但浊度和氨氮超标',
    operationRecords: [
      { time: '2025/3/27 16:13:28', action: '提交报表', operator: '张明远' },
      { time: '2025/3/27 17:30:15', action: '审核通过', operator: '王建国' }
    ]
  },
  {
    reportNo: 'WQR-202503002',
    reportName: '3月15日水质化验报表',
    samplingLocation: '进水口',
    samplingTime: '2025-03-15 09:30',
    createTime: '2025/3/15 15:13:28',
    creator: '张明远',
    inspector: '刘海洋',
    status: '待审核',
    testItems: [
      { item: 'pH值', value: '7.8', unit: '', standard: '6.5~8.5', result: '合格' },
      { item: '溶解氧', value: '6.5', unit: 'mg/L', standard: '≥5', result: '合格' }
    ],
    remarks: '',
    operationRecords: [
      { time: '2025/3/15 16:20:45', action: '提交报表', operator: '张明远' }
    ]
  }
])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 35
})

// 新建报表表单
const newReportForm = reactive({
  reportName: '',
  samplingLocation: '',
  samplingTime: '',
  inspector: '',
  testItems: [
    { item: '', value: '', unit: '', standard: '', result: '' }
  ],
  remarks: ''
})

// 检测项目选项
const testItemOptions = [
  { label: 'pH值', value: 'pH值' },
  { label: '浊度', value: '浊度' },
  { label: '余氯', value: '余氯' },
  { label: '总大肠菌群', value: '总大肠菌群' },
  { label: '氨氮', value: '氨氮' },
  { label: '溶解氧', value: '溶解氧' },
  { label: 'COD', value: 'COD' },
  { label: 'BOD', value: 'BOD' },
  { label: '总磷', value: '总磷' },
  { label: '总氮', value: '总氮' }
]

// 标准范围配置
const standardRanges = {
  'pH值': { min: 6.5, max: 8.5, unit: '' },
  '浊度': { max: 1, unit: 'NTU' },
  '余氯': { min: 0.05, unit: 'mg/L' },
  '总大肠菌群': { max: 0, unit: 'CFU/10mL' },
  '氨氮': { max: 0.5, unit: 'mg/L' },
  '溶解氧': { min: 5, unit: 'mg/L' },
  'COD': { max: 30, unit: 'mg/L' },
  'BOD': { max: 10, unit: 'mg/L' },
  '总磷': { max: 0.5, unit: 'mg/L' },
  '总氮': { max: 1.0, unit: 'mg/L' }
}

// 当前查看的报表
const currentReport = ref({})

// 对话框显示状态
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)

// 表单引用
const reportForm = ref(null)

// 表单验证规则
const rules = reactive({
  reportName: [
    { required: true, message: '请输入报表名称', trigger: 'blur' }
  ],
  samplingLocation: [
    { required: true, message: '请输入采样地点', trigger: 'blur' }
  ],
  samplingTime: [
    { required: true, message: '请选择采样时间', trigger: 'change' }
  ],
  inspector: [
    { required: true, message: '请输入检测人员', trigger: 'blur' }
  ]
})

// 搜索处理
const handleSearch = () => {
  console.log('搜索条件:', searchForm)
  // 这里应该调用API获取数据
  pagination.currentPage = 1
  fetchReports()
}

// 重置搜索
const resetSearch = () => {
  searchForm.reportNo = ''
  searchForm.dateRange = []
  searchForm.status = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchReports()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchReports()
}

// 查看详情
const handleView = (row) => {
  currentReport.value = JSON.parse(JSON.stringify(row))
  showDetailDialog.value = true
}

// 删除报表
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除报表 ${row.reportNo} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API删除数据
    const index = tableData.value.findIndex(item => item.reportNo === row.reportNo)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      pagination.total -= 1
    }
    ElMessage.success('报表删除成功')
  }).catch(() => {
    // 取消操作
  })
}

// 审核通过
const handleApprove = (row) => {
  ElMessageBox.confirm(`确定要通过报表 ${row.reportNo} 的审核吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 更新状态
    row.status = '已处理'
    // 添加操作记录
    if (!row.operationRecords) row.operationRecords = []
    row.operationRecords.push({
      time: new Date().toLocaleString(),
      action: '审核通过',
      operator: '当前用户' // 这里应该替换为实际用户
    })
    
    // 更新表格中的数据
    const index = tableData.value.findIndex(item => item.reportNo === row.reportNo)
    if (index !== -1) {
      tableData.value[index] = row
    }
    
    ElMessage.success('报表审核通过')
    if (showDetailDialog.value) showDetailDialog.value = false
  }).catch(() => {
    // 取消操作
  })
}

// 审核驳回
const handleReject = (row) => {
  ElMessageBox.confirm(`确定要驳回报表 ${row.reportNo} 的审核吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 更新状态
    row.status = '待处理'
    // 添加操作记录
    if (!row.operationRecords) row.operationRecords = []
    row.operationRecords.push({
      time: new Date().toLocaleString(),
      action: '审核驳回',
      operator: '当前用户' // 这里应该替换为实际用户
    })
    
    // 更新表格中的数据
    const index = tableData.value.findIndex(item => item.reportNo === row.reportNo)
    if (index !== -1) {
      tableData.value[index] = row
    }
    
    ElMessage.success('报表已驳回')
    if (showDetailDialog.value) showDetailDialog.value = false
  }).catch(() => {
    // 取消操作
  })
}

// 添加检测项目
const addTestItem = () => {
  newReportForm.testItems.push({ item: '', value: '', unit: '', standard: '', result: '' })
}

// 移除检测项目
const removeTestItem = (index) => {
  if (newReportForm.testItems.length > 1) {
    newReportForm.testItems.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留一个检测项目')
  }
}

// 检测项目变化处理
const handleTestItemChange = (index) => {
  const item = newReportForm.testItems[index].item
  if (item && standardRanges[item]) {
    const range = standardRanges[item]
    newReportForm.testItems[index].unit = range.unit || ''
    if (range.min !== undefined && range.max !== undefined) {
      newReportForm.testItems[index].standard = `${range.min}~${range.max}`
    } else if (range.max !== undefined) {
      newReportForm.testItems[index].standard = `≤${range.max}`
    } else if (range.min !== undefined) {
      newReportForm.testItems[index].standard = `≥${range.min}`
    }
  } else {
    newReportForm.testItems[index].unit = ''
    newReportForm.testItems[index].standard = ''
  }
}

// 验证检测值
const validateTestValue = (index) => {
  const testItem = newReportForm.testItems[index]
  if (!testItem.item) {
    ElMessage.warning('请先选择检测项目')
    return
  }
  
  if (!testItem.value) {
    ElMessage.warning('请输入检测值')
    return
  }
  
  const numericValue = parseFloat(testItem.value)
  if (isNaN(numericValue)) {
    ElMessage.warning('检测值必须是数字')
    return
  }
  
  const range = standardRanges[testItem.item]
  if (!range) {
    testItem.result = '合格' // 没有标准范围默认合格
    return
  }
  
  if (range.min !== undefined && range.max !== undefined) {
    testItem.result = numericValue >= range.min && numericValue <= range.max ? '合格' : '不合格'
  } else if (range.max !== undefined) {
    testItem.result = numericValue <= range.max ? '合格' : '不合格'
  } else if (range.min !== undefined) {
    testItem.result = numericValue >= range.min ? '合格' : '不合格'
  } else {
    testItem.result = '合格' // 没有标准范围默认合格
  }
}

// 提交报表
const submitReport = async () => {
  try {
    // 验证基础表单
    await reportForm.value.validate()
    
    // 验证检测项目
    for (const item of newReportForm.testItems) {
      if (!item.item) {
        ElMessage.warning('请选择所有检测项目')
        return
      }
      if (!item.value) {
        ElMessage.warning('请输入所有检测值')
        return
      }
    }
    
    // 生成报表编号
    const newReportNo = `WQR-${new Date().getFullYear()}${(new Date().getMonth() + 1).toString().padStart(2, '0')}${tableData.value.length + 1}`
    
    // 创建新报表
    const newReport = {
      reportNo: newReportNo,
      reportName: newReportForm.reportName,
      samplingLocation: newReportForm.samplingLocation,
      samplingTime: newReportForm.samplingTime,
      createTime: new Date().toLocaleString(),
      creator: '当前用户', // 这里应该替换为实际用户
      inspector: newReportForm.inspector,
      status: '待审核',
      testItems: newReportForm.testItems.map(item => ({
        ...item,
        unit: standardRanges[item.item]?.unit || '',
        standard: standardRanges[item.item] ? 
          (standardRanges[item.item].min !== undefined && standardRanges[item.item].max !== undefined ? 
            `${standardRanges[item.item].min}~${standardRanges[item.item].max}` :
            standardRanges[item.item].max !== undefined ? 
              `≤${standardRanges[item.item].max}` :
              `≥${standardRanges[item.item].min}`) : '',
        result: item.result || '合格'
      })),
      remarks: newReportForm.remarks,
      operationRecords: [
        { time: new Date().toLocaleString(), action: '提交报表', operator: '当前用户' }
      ]
    }
    
    console.log('提交报表:', newReport)
    // 这里应该调用API提交数据
    
    // 模拟添加到表格
    tableData.value.unshift(newReport)
    pagination.total += 1
    
    ElMessage.success('报表创建成功')
    showCreateDialog.value = false
    
    // 重置表单
    Object.assign(newReportForm, {
      reportName: '',
      samplingLocation: '',
      samplingTime: '',
      inspector: '',
      testItems: [{ item: '', value: '', unit: '', standard: '', result: '' }],
      remarks: ''
    })
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 转换检测数据为详情表格格式
const transformTestData = (report) => {
  return report.testItems.map(item => ({
    item: item.item,
    value: item.value,
    unit: item.unit,
    standard: item.standard,
    result: item.result
  }))
}

// 获取报表数据
const fetchReports = () => {
  console.log('获取报表数据', pagination)
  // 这里应该调用API获取数据
}

// 根据状态获取标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '已处理':
      return 'success'
    case '待审核':
      return 'warning'
    case '待处理':
      return 'danger'
    default:
      return 'info'
  }
}

onMounted(() => {
  fetchReports()
})
</script>

<style scoped>
.water-report-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  margin-right: 5px;
}

/* 详情页样式 */
.detail-container {
  padding: 10px;
}

.detail-container h3 {
  margin: 20px 0 15px 0;
  color: #606266;
}
</style>